package cn.dong.edu.controller.admin;


import cn.dong.edu.domain.Teacher;
import cn.dong.edu.service.impl.TeacherServiceImpl;
import cn.dong.api.domain.CommonResult;
import cn.dong.edu.domain.Course;
import cn.dong.edu.domain.query.QueryTeacher;
import cn.dong.edu.feign.OssService;
import cn.dong.edu.service.impl.CourseServiceImpl;
import cn.dong.base.handler.CustomException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 讲师 前端控制器
 * </p>
 *
 * @author You-Dong
 * @since 2021-01-30
 */
@RestController
@RequestMapping("/edu/teacher")
@Slf4j
//@CrossOrigin
public class TeacherController {

    @Autowired
    private TeacherServiceImpl teacherService;

    @Autowired
    private OssService ossService;

    @Autowired
    private CourseServiceImpl courseService;

    /**
     * 查询全部的讲师，查询出所有讲师的姓名和id，用于下拉列表选择
     *
     * @return
     */
    @GetMapping("/findAll")
    public CommonResult<List<Teacher>> findAll() {
        QueryWrapper<Teacher> query = new QueryWrapper<Teacher>();
        query.select("id", "name");
        List<Teacher> list = teacherService.list(query);
        log.info("------>查询了全部的讲师：");
        return CommonResult.ok().data(list);
    }


    /**
     * 创建讲师
     *
     * @return
     */
    @PostMapping("/create")
    public CommonResult<String> create(@RequestBody Teacher t) {
        if (teacherService.save(t)) {
            log.info("------>创建了讲师：" + t);
            return CommonResult.ok();
        }
        log.error("------>创建讲师产生了错误：" + t);
        return CommonResult.error();
    }

    /**
     * 修改讲师
     *
     * @return
     */
    @PutMapping("/update")
    public CommonResult<String> update(@RequestBody Teacher t) {
        if (teacherService.updateById(t)) {
            log.warn("------>修改了讲师：" + t);
            return CommonResult.ok();
        }
        log.error("------>修改讲师失败！：" + t);
        return CommonResult.error().message("修改失败，该id不存在:" + t.getId());
    }

    /**
     * 根据id查询讲师
     *
     * @return
     */
    @GetMapping("/findById/{id}")
    public CommonResult<Teacher> findById(@PathVariable("id") Long id) {
        Teacher teacher = teacherService.getById(id);
        if (teacher == null) {
            log.error("------>查询结果为空：" + id);
            return CommonResult.error().message("空空如也");
        }
        log.info("------>根据id查询讲师！：" + id);
        return CommonResult.ok().data(teacher);
    }


    /**
     * 根据id删除讲师
     *
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public CommonResult<List<Teacher>> delete(@PathVariable("id") String id) {
        // 判断讲师是否引用着其他课程
        QueryWrapper<Course> wrapper = new QueryWrapper<Course>();
        wrapper.eq("teacher_id", id);
        if (courseService.count(wrapper) > 0) {
            throw new CustomException(40000, "当前讲师有正在引用的课程，请先删除课程");
        }
        // 删除讲师图片
        Teacher teacher = teacherService.getById(id);
        // 删除讲师
        if (!teacherService.removeById(id)) {
            return CommonResult.error();
        }
        return ossService.delFile(teacher.getAvatar());
    }


    /**
     * 分页查询讲师
     *
     * @return
     */
    @GetMapping("/findByPage/{current}/{size}")
    public CommonResult<List<Teacher>> findByPage(@PathVariable("current") Integer current,
                                                  @PathVariable("size") Integer size) {
        Page<Teacher> page = new Page<Teacher>(current, size);
        // 分页查询
        IPage<Teacher> p = teacherService.page(page, null);
        // 当前多少页
        long currents = p.getCurrent();
        // 总页数
        long pages = p.getPages();
        // 每页显示多少个
        long sizes = p.getSize();
        // 一共又多少条数据
        long totals = p.getTotal();
        // 获取的全部数据
        List<Teacher> records = p.getRecords();
        // 装进容器
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("current", currents);
        map.put("pages", pages);
        map.put("size", sizes);
        map.put("total", totals);
        map.put("data", records);
        return CommonResult.ok().data(map);
    }


    /**
     * 分页查询组合条件查询讲师
     *
     * @param current
     * @param size
     * @return
     */
    @PostMapping("/findByCondition/{current}/{size}")
    public CommonResult findByCondition(@PathVariable("current") Integer current,
                                        @PathVariable("size") Integer size,
                                        @RequestBody(required = false) QueryTeacher queryTeacher) {
        IPage<Teacher> page = teacherService.findByCondition(current, size, queryTeacher);
        return CommonResult.ok().data(page);
    }


}

